package com.bite.demo.mail;

import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

@Slf4j
@Configuration
public class Mail {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private MailProperties mailProperties;
    public void sendMail(String to,String content){
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(message,false);
            String from=mailProperties.getUsername();
            helper.setFrom(from,mailProperties.getProperties().getOrDefault("personal",from));
            helper.setTo(to);
            // 邮件标题
            helper.setSubject(mailProperties.getProperties().getOrDefault("subject", "告警通知"));
            // 邮件正文，第二个参数表示是否是HTML正文
            helper.setText(content, true);
            mailSender.send(message);
        }catch (Exception e){
            log.error("发送邮件失败, e: ", e);
        }
    }
}
